package com.example.ec.controller;


import com.example.ec.model.Goods;
import com.example.ec.model.Product;
import com.example.ec.service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("product")
public class ProductController extends BaseController {
        private final ProductService productService;

    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    @PostMapping("create")
    private String create(Product product, MultipartFile file) throws IOException {
        File dir = new File(application.getRealPath("/pictures"));
        String contentType = file.getContentType();

        String picture = UUID.randomUUID()+"."+StringUtils.getFilenameExtension(file.getOriginalFilename());
        file.transferTo(new File(dir,picture));
        product.setPicture(picture);
        productService.create(product);
     return "redirect:/product/queryAll";
    }

    @GetMapping("queryAll")
    private String queryAll(Product product){
        session.setAttribute("products",productService.queryList("queryAll",product));
        return "redirect:/admin.jsp";
    }

    @GetMapping("queryById/{id}")
    private String queryById(@PathVariable("id") int id){
       session.setAttribute("product",productService.queryById(id));
        return "redirect:/edit.jsp";
    }

    @PostMapping ("modify")
    private String modify(Product product,MultipartFile file) throws IOException {
        if(file.getSize()!=0){
            File dir = new File(application.getRealPath("/pictures"));
            String picture = UUID.randomUUID()+"."+StringUtils.getFilenameExtension(file.getOriginalFilename());
            file.transferTo(new File(dir,picture));
            product.setPicture(picture);
        }

        productService.modify(product);
        return "redirect:/product/queryAll";
    }

    @GetMapping("removeById/{id}")
    private String removeById(@PathVariable("id") int id){
        productService.removeById(id);
        return "redirect:/product/queryAll";
    }

    @PostMapping("query")
    private String query(Product product){
        session.setAttribute("indexProducts",productService.queryList("query",product));
        return "redirect:/index.jsp";
    }
}
